package com.iflytek.jcy.supervise.clue.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iflytek.jcy.supervise.clue.common.enums.ResultEnum;
import com.iflytek.jcy.supervise.clue.common.exception.BaseException;
import com.iflytek.jcy.supervise.clue.common.pojo.CommonResponse;
import com.iflytek.jcy.supervise.clue.dto.QueryClueDeatilDTO;
import com.iflytek.jcy.supervise.clue.dto.QueryClueCollectionListDTO;
import com.iflytek.jcy.supervise.clue.dto.response.ClueCollectionDTO;
import com.iflytek.jcy.supervise.clue.dto.response.ClueCollectionListDTO;
import com.iflytek.jcy.supervise.clue.entity.ClueCollection;
import com.iflytek.jcy.supervise.clue.entity.ClueCollectionMap;
import com.iflytek.jcy.supervise.clue.entity.CluePushDetail;
import com.iflytek.jcy.supervise.clue.mapper.ClueCollectionMapMapper;
import com.iflytek.jcy.supervise.clue.mapper.ClueCollectionMapper;
import com.iflytek.jcy.supervise.clue.mapper.CluePushDetailMapper;
import com.iflytek.jcy.supervise.clue.mapper.TaskDetailMapper;
import com.iflytek.jcy.supervise.clue.service.IClueCollectionService;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iflytek.jcy.supervise.clue.entity.TaskDetail;

/**
 * <p>
 * 线索集表 服务实现类
 * </p>
 *
 * @author dgyu
 * @since 2022-10-20
 */
@Service
public class ClueCollectionServiceImpl extends ServiceImpl<ClueCollectionMapper, ClueCollection> implements IClueCollectionService {
    
	private static final Logger	logger = LoggerFactory.getLogger(ClueCollectionServiceImpl.class);
	
	@Autowired
	private ClueCollectionMapper clueCollectionMapper;
	@Autowired
	private ClueCollectionMapMapper clueCollectionMapMapper;
	@Autowired
	private TaskDetailMapper taskDetailMapper;
	@Autowired
	private CluePushDetailMapper cluePushDetailMapper;
	
	@Override
	public List<ClueCollectionDTO> getCollectionByClueResultId(Integer taskDetailId,String rybm) {
		TaskDetail taskDetail=this.taskDetailMapper.selectById(taskDetailId);
		if(null == taskDetail) {
			logger.error("线索不存在taskDetailId:{}",taskDetailId);
			throw new BaseException(ResultEnum.EXCEPTION, "线索不存在taskDetailId:{}"+taskDetailId);
		}
		List<ClueCollectionDTO> list1= clueCollectionMapper.getCollectionByClueResultId(taskDetailId,rybm,taskDetail.getTaskId());
		/*list1.forEach(v->{
			v.setSelected(true);
		});*/
		List<ClueCollectionDTO> list2= clueCollectionMapper.getOtherCollectionByClueResultId(taskDetailId,rybm,taskDetail.getTaskId());
		list1.addAll(list2);
		list1.sort(Comparator.comparing(ClueCollectionDTO::getCreateTime).reversed());
		return list1;
	}

	@Override
	public CommonResponse addClueCollection(JSONObject jSONObject) {
		String name=jSONObject.getString("name");
		String rybm=jSONObject.getString("rybm");
		Integer taskId=jSONObject.getInteger("taskId");
		if(StringUtils.isEmpty(rybm)) {
			return CommonResponse.failed(ResultEnum.CLUE_RYBM_IS_NULL);
		}
		if(StringUtils.isEmpty(name)) {
			return CommonResponse.failed(ResultEnum.CLUE_NAME_IS_NULL);
		}
		if(taskId == null || taskId == 0) {
			return CommonResponse.failed(ResultEnum.TASK_ID_IS_NULL);
		}
		LambdaQueryWrapper<ClueCollection> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(ClueCollection::getName, name);
		lambdaQueryWrapper.eq(ClueCollection::getRybm, rybm);
		lambdaQueryWrapper.eq(ClueCollection::getIsDelete, 0);
		Long rows=this.baseMapper.selectCount(lambdaQueryWrapper);
		if(rows > 0L) {
			return CommonResponse.failed(ResultEnum.CLUE_COLLECTION_NAME_IS_EXIST);
		}
		ClueCollection entity=new ClueCollection();
		entity.setName(name);
		entity.setCreateTime(new Date());
		entity.setRybm(rybm);
		entity.setTaskId(taskId);
		this.baseMapper.insert(entity);
		return CommonResponse.success(entity.getId());
	}

	@Override
	public IPage<ClueCollectionListDTO> listCollection(QueryClueCollectionListDTO queryClueCollectionListDTO) {
		IPage<QueryClueCollectionListDTO> page = new Page<>(queryClueCollectionListDTO.getPageNo(), queryClueCollectionListDTO.getPageSize());
		IPage<ClueCollectionListDTO> pageCollection = clueCollectionMapper.listCollection(page,queryClueCollectionListDTO.getRybm(),queryClueCollectionListDTO.getTaskId());
		List<ClueCollectionListDTO> records = pageCollection.getRecords();
		if (CollectionUtils.isNotEmpty(records)) {
			List<Integer> idList = records.stream().map(ClueCollectionListDTO::getId).collect(Collectors.toList());
			
			LambdaQueryWrapper<ClueCollectionMap> lambdaQueryWrapper=new LambdaQueryWrapper<>();
			lambdaQueryWrapper.in(ClueCollectionMap::getCollectionId, idList);
			List<ClueCollectionMap> clueCollectionMapList = clueCollectionMapMapper.selectList(lambdaQueryWrapper);
			if (CollectionUtils.isNotEmpty(clueCollectionMapList)) {
				Map<Integer, List<ClueCollectionMap>> groupMap = clueCollectionMapList.stream().collect(Collectors.groupingBy(ClueCollectionMap::getCollectionId));
				Map<Integer, Set<String>> map = new HashMap<>();
				Map<Integer, Boolean> mapCanDelete = new HashMap<>();
				Map<Integer, List<TaskDetail>> clueResultMap = new HashMap<>();
				groupMap.forEach((collectionId, v) -> {
					// 任务详情id集合
					List<Integer> clueResultIdList = v.stream().map(ClueCollectionMap::getTaskDetailId).collect(Collectors.toList());
					List<TaskDetail> taskDetailList = taskDetailMapper.selectBatchIds(clueResultIdList);
					clueResultMap.put(collectionId, taskDetailList);
					
					Set<String> set = taskDetailList.stream().map(TaskDetail::getExceptionLogic).collect(Collectors.toSet());
					map.put(collectionId, set);
					//查看线索有没有被推送过 被推送过则不能显示删除按钮
					LambdaQueryWrapper<CluePushDetail> cluePushDetailLambdaQueryWrapper=new LambdaQueryWrapper<>();
					cluePushDetailLambdaQueryWrapper.in(CluePushDetail::getDetailId, clueResultIdList);
					Long count = this.cluePushDetailMapper.selectCount(cluePushDetailLambdaQueryWrapper);
					mapCanDelete.put(collectionId,count > 0L ? false:true);
				});
				records.forEach(collection -> {
					Integer collectionId = collection.getId();
					Set<String> set = map.get(collectionId);
					List<TaskDetail> list = clueResultMap.get(collectionId);
					Integer clueNum = 0;
					Integer exceptionNum=0;
					String exceptionLogic = "";
					if (CollectionUtils.isNotEmpty(set)) {
						exceptionNum = CollectionUtils.size(set);
						exceptionLogic = set.stream().collect(Collectors.joining("、"));
					}
					if(CollectionUtils.isNotEmpty(list)){
						clueNum=CollectionUtils.size(list);
					}
					collection.setClueNum(clueNum);
					collection.setExceptionNum(exceptionNum);
					collection.setExceptionLogic(exceptionLogic);
					collection.setCanDelete(mapCanDelete.getOrDefault(collectionId,true));
				});
			}
		}
		return pageCollection;
	}

	@Override
	public IPage<TaskDetail> collectionDetail(QueryClueDeatilDTO queryClueDeatilDTO) {
		Integer collectionId = queryClueDeatilDTO.getCollectionId();
		String keyword = queryClueDeatilDTO.getKeyword();
		// 查询关系表detailId集合
		LambdaQueryWrapper<ClueCollectionMap> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(ClueCollectionMap::getCollectionId, collectionId).orderByDesc(ClueCollectionMap::getUpdateTime);
		List<ClueCollectionMap> clueCollectionMapList = clueCollectionMapMapper.selectList(lambdaQueryWrapper);
		if (CollectionUtils.isEmpty(clueCollectionMapList)) {
			return null;
		}
		List<Integer> detailIds = clueCollectionMapList.stream().map(ClueCollectionMap::getTaskDetailId).collect(Collectors.toList());
		//id逗号分隔
		String detailSplitIds = clueCollectionMapList.stream().map(cc -> cc.getTaskDetailId() + "").collect(Collectors.joining(","));
		//拼接Sql
		StringBuilder builder = new StringBuilder("order by field(id,");
		builder.append(detailSplitIds).append(")");
		LambdaQueryWrapper<TaskDetail> queryWrapper = new LambdaQueryWrapper<>();
		//order by field(task_detail_id,281,285) 按照id特殊排序
		queryWrapper.last(builder.toString());
		queryWrapper.in(TaskDetail::getId, detailIds);
		if (StringUtils.isNotEmpty(keyword)) {
			queryWrapper.and(wrapper -> wrapper.like(TaskDetail::getSupervisionObjectName, keyword)
					.or().like(TaskDetail::getExceptionLogic, keyword)
					.or().like(TaskDetail::getSupervisionPointName, keyword)
					.or().like(TaskDetail::getSupervisionObject, keyword)
					.or().like(TaskDetail::getExceptionTypeDesc, keyword)
					.or().like(TaskDetail::getSupervisionPointContent, keyword));
		}
		IPage<TaskDetail> page = new Page<>(queryClueDeatilDTO.getPageNo(), queryClueDeatilDTO.getPageSize());
		IPage<TaskDetail> pageTaskDetail = taskDetailMapper.selectPage(page, queryWrapper);
		return pageTaskDetail;
	}

	@Override
	public Integer deleteCollection(Integer collectionId) {
		LambdaUpdateWrapper<ClueCollection> wrapper = new LambdaUpdateWrapper<ClueCollection>()
				.set(ClueCollection::getIsDelete, 1)
				.set(ClueCollection::getUpdateTime, new Date())
				.eq(ClueCollection::getId, collectionId);
		// 删除线索集线索关系表
		LambdaUpdateWrapper<ClueCollectionMap> wrapper3 = new LambdaUpdateWrapper<>();
		wrapper3.eq(ClueCollectionMap::getCollectionId, collectionId);
		this.clueCollectionMapMapper.delete(wrapper3);
		int rows = this.baseMapper.update(null, wrapper);
		return rows;
	}

	@Override
	public Integer collectionFeedback(JSONObject jSONObject) {
		Integer id = jSONObject.getInteger("id");
		Integer evaluationResult = jSONObject.getInteger("evaluationResult");
		String bmsah = jSONObject.getString("bmsah");
		String ajmc = jSONObject.getString("ajmc");
		String info = jSONObject.getString("info");
		LambdaUpdateWrapper<ClueCollection> wrapper = new LambdaUpdateWrapper<>();
		if (evaluationResult != null && evaluationResult >= 0) {
			wrapper.set(ClueCollection::getEvaluationResult, evaluationResult);
		}
		if (!StringUtils.isEmpty(bmsah)) {
			wrapper.set(ClueCollection::getBmsah, bmsah);
		}
		if (!StringUtils.isEmpty(ajmc)) {
			wrapper.set(ClueCollection::getAjmc, ajmc);
		}
		if (!StringUtils.isEmpty(info)) {
			wrapper.set(ClueCollection::getInfo, info);
		}
		wrapper.set(ClueCollection::getUpdateTime, new Date());
		wrapper.eq(ClueCollection::getId, id);
		int rows = clueCollectionMapper.update(null, wrapper);
		return rows;
	}
}
